<template>
    <div class="article-list">
        <van-pull-refresh v-model="isReFreshLoading" :success-text="refreshSuccessText" :success-duration="1500" @refresh="onRefresh">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error" error-text="请求失败，点击重新加载">
                <article-item  v-for="(article, index) in list" :key="index" :article="article"></article-item>
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item.vue";
export default {
  components: {
    ArticleItem,
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [], //存储列表数据的数组
      loading: false, //控制加载中loading状态
      finished: false, //控制数据加载结束状态
      timestamp: null,
      error: false,
      isReFreshLoading: false, //控制下拉刷新的loading状态
      refreshSuccessText: "刷新成功",
    };
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), //简单理解就是请求数据的页码
        });
        // 模拟随机失败的情况
        // if (Math.random() > 0.5) {
        //   JSON.parse("assas");
        // }
        const { results } = data.data;
        this.list.push(...results);

        this.loading = false;

        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (error) {
        this.error = true;
        this.loading = false;
      }
    },
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(), //简单理解就是请求数据的页码
        });
        // if (Math.random() > 0.2) {
        //   JSON.parse("assas");
        // }
        const { results } = data.data;
        this.list.unshift(...results);
        this.isReFreshLoading = false;
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`;
      } catch (error) {
        this.refreshSuccessText = "请求失败";
        this.isReFreshLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>